﻿using System;
using System.Collections.Generic;

namespace RobotRemoteController
{
    public class FiniteStateMachine<InputType>
    {
        // 定义委托
        public delegate string StateTransferHandler(InputType input);
        public delegate void OnStateTransferHandler(string currentState, string nextState);

        // 定义状态转移事件
        public event OnStateTransferHandler OnStateTransfer;

        // 保存状态机的状态及其状态转移函数
        private Dictionary<string, StateTransferHandler> stateTransitionHandlers = new Dictionary<string, StateTransferHandler>();
        // 保存当前状态
        public string currentState = "";
        // 保存初态
        public string startState = "";

        // 构造函数
        public FiniteStateMachine(string startState)
        {
            this.startState = startState.ToUpper();
            currentState = startState;
        }

        // 添加状态及其转移函数
        public FiniteStateMachine<InputType> AddState(string state, Func<InputType, string> handler)
        {
            string _state = state.ToUpper();
            StateTransferHandler _handler = new StateTransferHandler(handler);
            if (!stateTransitionHandlers.ContainsKey(_state))
            {
                stateTransitionHandlers.Add(_state, _handler);
            }
            else
            {
                stateTransitionHandlers[_state] = _handler;
            }
            return this;
        }

        // 根据输入进行状态转移
        public void Next(InputType input)
        {
            string curState = currentState;
            string next = stateTransitionHandlers[currentState.ToUpper()](input);
            // 调用事件
            if (OnStateTransfer != null)
                OnStateTransfer(curState, next);
            currentState = next;
        }

        // 根据一连串输入进行连续状态转移
        public void NextArray(InputType[] inputList)
        {
            foreach(InputType input in inputList)
            {
                Next(input);
            }
        }
    }
}
